package com.pda.yuanjing.pages.syyk;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.JieDianBeanIn;
import com.pda.yuanjing.beanout.JDBeanNewOut;
import com.pda.yuanjing.beanout.NoBillBeanOut;
import com.pda.yuanjing.beanout.SCBeanOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.error.ErrorDialog;
import com.pda.yuanjing.dialog.store.StoreDialog;
import com.pda.yuanjing.message.MessageBus;
import com.pda.yuanjing.thread.CodeBeans;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.config.ApiYJ;
import com.public_module.config.SetConfig;
import com.public_module.tools.DateUtils;
import com.public_module.tools.DensityUtil;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ScanfActivity extends BaseActivity<ScanfModel, ScanfView, ScanfPresent> implements ScanfView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvdht)
    TextView tvdht;
    @BindView(R.id.dh)
    EditText dh;
    @BindView(R.id.tvlc)
    TextView tvlc;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.tvjd)
    TextView tvjd;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.tvkf)
    TextView tvkf;
    @BindView(R.id.ll3)
    LinearLayout ll3;
    @BindView(R.id.tvgys)
    TextView tvgys;
    @BindView(R.id.ll4)
    LinearLayout ll4;
    @BindView(R.id.tvjxs)
    TextView tvjxs;
    @BindView(R.id.ll5)
    LinearLayout ll5;
    @BindView(R.id.tvtmt)
    TextView tvtmt;
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.tvstore)
    TextView tvstore;
    @BindView(R.id.tvstorev)
    TextView tvstorev;
    @BindView(R.id.rlk)
    RelativeLayout rlk;
    @BindView(R.id.tvpro)
    TextView tvpro;
    @BindView(R.id.tvprov)
    TextView tvprov;
    @BindView(R.id.rlp)
    RelativeLayout rlp;
    @BindView(R.id.ivd)
    ImageView ivd;
    @BindView(R.id.tvjc)
    TextView tvjc;
    @BindView(R.id.etres)
    TextView etres;
    @BindView(R.id.lls)
    LinearLayout lls;
    @BindView(R.id.tvms)
    TextView tvms;
    @BindView(R.id.etreason)
    EditText etreason;
    @BindView(R.id.llms)
    LinearLayout llms;
    @BindView(R.id.tv00)
    TextView tv00;
    @BindView(R.id.tv000)
    TextView tv000;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.tvres)
    TextView tvres;
    @BindView(R.id.tvs)
    TextView tvs;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tvwait)
    TextView tvwait;

    private String TAG = "ScanfActivity";
    int scanfState = 0;
    boolean flag = true;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    String key = "";
    CodeBeans codeBeans = new CodeBeans();
    int waitNum = 0;
    Thread upThread = null;
    boolean exit = false;
    CodeAdapter codeAdapter;
    List<NoBillBeanOut.DataBean.CodeInfoBean> plist = new ArrayList<>();
    String sid = "-1";
    StoreDialog storeDialog;
    ErrorDialog errorDialog;
    int total = 0;
    JDBeanNewOut.DataBean jdBeanNewOut;

    protected void initdata() {
        jdBeanNewOut = (JDBeanNewOut.DataBean)getIntent().getSerializableExtra(PDApp.process);
        tvTitle.setText("溯源移库 " + SharedPreferencesManger.getRealName());
        dh.setText(DateUtils.stampToDateTime(new Date().getTime()));
        tvwait.setText(waitNum + "");
        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                        tvs.setText(dataa.getStr());
                        scanfState = dataa.getType();
                        if (scanfState == -1) {
                            tvs.setBackgroundResource(R.color.smalltext);
                        } else {
                            tvs.setBackgroundResource(R.color.green);
                        }
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        String ss = StringProcess.codeMat(string);
                        if (!PDApp.scanf) {
                            return;
                        }
                        if (!PDApp.scanfp) {
                            getRes("1", ss);
                            return;
                        }
                        if (!PDApp.scanfs) {
                            getRes("2", ss);
                            return;
                        }
                        if (scanfState == -1) {
                            showres("网络异常,请检查网络");
                            return;
                        }
                        if (dh.getText().toString().length() == 0) {
                            showres("请填写单号");
                            return;
                        }
                        if (sid.equals("-1")) {
                            showres("请选择库房");
                            return;
                        }
                        CodeBeans.Code cbean = new CodeBeans.Code();
                        cbean.setStr(ss);
                        cbean.setFlag(flag);
                        codeBeans.addCode(cbean);
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        upThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!exit) {
                    if (codeBeans!=null && codeBeans.getCodes().size() > 0) {
                        try {
                            presenter.scanfCodeNobill(dh.getText().toString(),  codeBeans.getCodes().get(0).getStr(), sid, codeBeans);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        upThread.start();
        codeAdapter = new CodeAdapter(this, plist);
        listview.setAdapter(codeAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yk_scanf);
        ButterKnife.bind(this);
        initdata();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
        EventBus.getDefault().unregister(this);
        exit = true;
        upThread = null;
    }

    @Override
    public ScanfModel createModel() {
        return new ScanfModelImpl(this);
    }

    @Override
    public ScanfView createView() {
        return this;
    }

    @Override
    public ScanfPresent createPresenter() {
        return new ScanfPresent();
    }


    @OnClick({R.id.iv_title_left, R.id.logine, R.id.etres, R.id.ivd, R.id.tvkf, R.id.tvprov})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvkf:
                storeDialog = new StoreDialog(mContext, R.style.CommentDialog, new StoreDialog.PriorityListener() {
                    @Override
                    public void setActivityText(String str, String str1) {
                        tvkf.setText(str);
                        sid = str1;
                        storeDialog.dismiss();
                    }
                });
                WindowManager.LayoutParams lp = storeDialog.getWindow().getAttributes();
                lp.gravity = Gravity.CENTER;
                storeDialog.show();
                break;
            case R.id.logine:
                if (scanfState == -1) {
                    showres("网络异常,请检查网络");
                    return;
                }
                if (dh.getText().toString().length() == 0) {
                    showres("请填写单号");
                    return;
                }
                if (sid.equals("-1")) {
                    showres("请选择库房");
                    return;
                }
                CodeBeans.Code cbean = new CodeBeans.Code();
                cbean.setStr(loginId.getText().toString());
                cbean.setFlag(flag);
                codeBeans.addCode(cbean);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void showres(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                voiceUtils.voiceWarn();
                tvres.setText(str);
                loginId.setText("");
                tvwait.setText(codeBeans.getCodes().size() + "");
                plist.clear();
                codeAdapter.notifyDataSetChanged();
                if (PDApp.cidInfoBeanOut.getData()!=null && PDApp.cidInfoBeanOut.getData().isShowErrorDialog()) {
                    errorDialog = new ErrorDialog(mContext, str, R.style.CommentDialog, new ErrorDialog.PriorityListener() {
                        @Override
                        public void setActivityText() {
                        }
                    });
                    WindowManager.LayoutParams lp = errorDialog.getWindow().getAttributes();
                    lp.gravity = Gravity.CENTER;
                    errorDialog.show();
                    Window window = errorDialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams attrs = window.getAttributes();
                    attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                    attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    errorDialog.getWindow().setAttributes(attrs);
                }
            }
        });
    }

    @Override
    public void onshowSuccessresNoBill(NoBillBeanOut.DataBean codeInfo) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(codeInfo==null){
                    return;
                }
                if (codeInfo.getCode() == 0) {
                    tvres.setText("数码处理完成");
                    loginId.setText("");
                    tvwait.setText(codeBeans.getCodes().size() + "");
                    total++;
                    tv000.setText(total + "");
                    if (codeInfo != null) {
                        plist.clear();
                        plist.add(codeInfo.getCodeInfo());
                        codeAdapter.notifyDataSetChanged();
                    }
                } else {
                    voiceUtils.voiceWarn();
                    tvres.setText(codeInfo.getStr());
                    loginId.setText("");
                    tvwait.setText(codeBeans.getCodes().size() + "");
                    if (codeInfo != null) {
                        plist.clear();
                        plist.add(codeInfo.getCodeInfo());
                        codeAdapter.notifyDataSetChanged();
                    }
                    if (PDApp.cidInfoBeanOut.getData()!=null && PDApp.cidInfoBeanOut.getData().isShowErrorDialog()) {
                        errorDialog = new ErrorDialog(mContext, codeInfo.getStr(), R.style.CommentDialog, new ErrorDialog.PriorityListener() {
                            @Override
                            public void setActivityText() {
                            }
                        });
                        WindowManager.LayoutParams lp = errorDialog.getWindow().getAttributes();
                        lp.gravity = Gravity.CENTER;
                        errorDialog.show();
                        Window window = errorDialog.getWindow();
                        window.setBackgroundDrawableResource(android.R.color.transparent);
                        WindowManager.LayoutParams attrs = window.getAttributes();
                        attrs.width = (int) DensityUtil.dp2px(ScanfActivity.this, 300);
                        attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                        errorDialog.getWindow().setAttributes(attrs);
                    }
                }
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageBus messageBus) {
    }

    public void getRes(String id, String code) {
        try {
            showProgress();
            Gson gson = new Gson();
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(SetConfig.getConnectTimeout(), TimeUnit.SECONDS)
                    .readTimeout(SetConfig.getReadTimeout(), TimeUnit.SECONDS)
                    .writeTimeout(SetConfig.getWriteTimeout(), TimeUnit.SECONDS)
                    .followRedirects(false)
                    .build();
            ApiYJ apisync = new Retrofit.Builder()
                    .baseUrl("http://" + SharedPreferencesManger.getHostName() + "/")
                    .client(client)
                    .build().create(ApiYJ.class);

            JieDianBeanIn jieDianBeanIn = new JieDianBeanIn();
            jieDianBeanIn.setAction("SY_QueryProdcutStoreByCode");
            jieDianBeanIn.setCid(SharedPreferencesManger.getCid());
            jieDianBeanIn.setUserID(SharedPreferencesManger.getUid());
            jieDianBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
            jieDianBeanIn.setBaseType(id);
            jieDianBeanIn.setCodecc(code);

            RequestBody body = RequestBody.create(SetConfig.JSON, gson.toJson(jieDianBeanIn));
            final Call<ResponseBody> call = apisync.downLoad(body);
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response<ResponseBody> response = call.execute();
                        if (response.isSuccessful()) {
                            LogUtils.e(StringProcess.responsetoString(response.body()));
                            SCBeanOut scBeanOut = gson.fromJson(StringProcess.responsetoString(response.body()), SCBeanOut.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (id.equals("1")) {
                                    } else if (id.equals("2")) {
                                        storeDialog.dismiss();
                                        if (scBeanOut.getData().getIdStr().equals("-1")) {
                                            showMsg("未匹配到库房信息");
                                        } else {
                                            tvstorev.setText(scBeanOut.getData().getNameStr());
                                            sid = scBeanOut.getData().getIdStr();
                                        }
                                    }
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            hideProgress();
            return;
        }
    }
}
